package com.uetoken.cn.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.support.v4.app.NotificationCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.tencent.smtt.sdk.QbSdk;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.activity.SplashActivity;
import com.uetoken.cn.activity.WebActivity;
import com.uetoken.cn.bean.PushMessageBean;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.getui.GeTuiPushService;
import com.uetoken.cn.getui.GeTuiReceiverIntentService;
import com.uetoken.cn.language.MultiLanguageUtil;
import com.uetoken.cn.utils.MediaLoader;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 谢杨
 * @time 2018/7/16 11:20
 * @class 描述:自定义Application
 */
public class MyApplication extends Application {
    private static MyApplication app;
    private final String mFilePath = "/uetoken/Crash";
    private Handler mHandler;
    private static DemoHandler mDemoHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        if (mDemoHandler == null) {
            mDemoHandler = new DemoHandler();
        }
        //第三方库的初始化
        initThirdLibrary();
        //应用生命周期回调的注册方法
        registerActivityLifecycle();
    }

    @SuppressLint("MissingPermission")
    private void initThirdLibrary() {
        //初始化工具库
        Utils.init(this);

        LogUtils.dTag("CrashUtils==", "CrashUtils = " + getSDPath().getAbsolutePath());
        CrashUtils.init(getSDPath());

        //初始化语言工具类
        MultiLanguageUtil.init(this);

        //初始化个推
        PushManager.getInstance().initialize(this, GeTuiPushService.class);
        PushManager.getInstance().registerPushIntentService(this, GeTuiReceiverIntentService.class);
        //拍照和图片裁剪框架初始化
        Album.initialize(AlbumConfig.newBuilder(this)
                .setAlbumLoader(new MediaLoader()).build());
        initUMeng();
        initTencentX5();
    }

    private void initUMeng() {
        /**
         * 注意: 即使您已经在AndroidManifest.xml中配置过appkey和channel值，
         *     也需要在App代码中调用初始化接口（如需要使用AndroidManifest.xml中配置好的appkey和channel值，
         *     UMConfigure.init调用中appkey和channel参数请置为null）。
         *
         *      初始化common库
         *           参数1:上下文，不能为空
         *           参数2:【友盟+】 AppKey
         *           参数3:【友盟+】 Channel
         *           参数4:设备类型，UMConfigure.DEVICE_TYPE_PHONE为手机、UMConfigure.DEVICE_TYPE_BOX为盒子，默认为手机
         *           参数5:Push推送业务的secret
         */
        //初始化组件化基础库, 统计SDK/推送SDK/分享SDK都必须调用此初始化接口
        UMConfigure.setLogEnabled(true);
        UMConfigure.init(this, "5bbaf584b465f592c90000ae", "uetoken", UMConfigure.DEVICE_TYPE_PHONE, "");
        PlatformConfig.setWeixin("wx019d7dc717328f62", "2e916ff767facd6e07c9803f14196b16");
        PlatformConfig.setQQZone("101510946", "13adf433a224d2c52bba560e2d7d1789");
    }

    /**
     * 腾讯X5浏览器SDK初始化
     */
    private void initTencentX5() {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    public Handler getHandler() {
        return mHandler;
    }

    public void setHandler(Handler handler) {
        mHandler = handler;
    }

    private void registerActivityLifecycle() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MultiLanguageUtil.getInstance().setConfiguration();
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
//
//                if (activity instanceof MainActivity) {
//                    LogUtils.dTag("registerActivityLifecycle==", "===onActivityDestroyed===");
//                }
//                updateAPPIcon();
//                if (!AppUtils.isAppRunning("com.uetoken.cn")){

//                }
            }
        });
    }


    public static MyApplication getInstance() {
        return app;
    }

    /**
     * 获取sd卡路径
     *
     * @return
     */
    private File getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            // 这里可以修改为你的路径
            sdDir = new File(Environment.getExternalStorageDirectory() + mFilePath);
            if (!sdDir.exists()) {
                sdDir.mkdirs();
            }
        }
        return sdDir;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        MultiLanguageUtil.getInstance().setConfiguration();
    }

    public static void sendMessage(Message msg) {
        mDemoHandler.sendMessage(msg);
    }

    public class DemoHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    String context = (String) msg.obj;
                    sendSimplestNotificationWithAction(context);
                    break;
            }
        }
    }

    // 通知栏消息
    private int messageNotificationID = 1;
    private Notification messageNotification = null;
    private NotificationManager messageNotificatioManager = null;
    private NotificationChannel Channel = null;
    private static final int PUSH_NOTIFICATION_ID = (0x81125);
    private static final String PUSH_CHANNEL_ID = "UE_PUSH_NOTIFY_ID";
    private static final String PUSH_CHANNEL_NAME = "UE_PUSH_NOTIFY_NAME";
    private int pushNum = 0;

    /**
     * 发送一个点击跳转到MainActivity的消息
     */
    private void sendSimplestNotificationWithAction(String contentStr) {
        String mUrl = "";
        String mTitle = "";
        String mContent = "";
        try {
            PushMessageBean pushMessageBean = new Gson().fromJson(contentStr, PushMessageBean.class);
            mUrl = pushMessageBean.getUrl();
            mTitle = pushMessageBean.getTitle();
            mContent = pushMessageBean.getContent();
        } catch (Exception e) {
            e.printStackTrace();
            mContent = contentStr;
        }


        if (messageNotificatioManager == null) {
            messageNotificatioManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
        NotificationCompat.Builder mBuilder;
        //判断是否是8.0Android.O
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (Channel == null) {
                Channel = new NotificationChannel(PUSH_CHANNEL_ID,
                        PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                Channel.setLightColor(Color.GREEN);
                Channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            }
            messageNotificatioManager.createNotificationChannel(Channel);
            mBuilder = new NotificationCompat.Builder(this, PUSH_CHANNEL_ID);
        } else {
            mBuilder = new NotificationCompat.Builder(getApplicationContext());
            mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        }
        Intent notificationIntent;
        if (isAppAlive(this, AppUtils.getAppPackageName())) {
            if ("http".equals(mUrl)) {
                notificationIntent = new Intent(this, WebActivity.class);
                notificationIntent.putExtra(Constant.TO_WEBVIEW_URL, mUrl);
            } else {
                notificationIntent = new Intent(this, MainActivity.class);
            }
        } else {
            notificationIntent = new Intent(this, SplashActivity.class);
        }
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(this, PUSH_NOTIFICATION_ID, notificationIntent, 0);
        mBuilder.setContentTitle(mTitle)//设置通知栏标题
                .setContentText(mContent)//设置通知栏内容
                .setContentIntent(intent) //设置通知栏点击意图
                .setNumber(++pushNum) //设置通知集合的数量
                .setTicker(mTitle + ":" + mContent) //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSmallIcon(R.mipmap.ic_logo);//设置通知小ICON
        messageNotification = mBuilder.build();
        messageNotification.flags |= Notification.FLAG_AUTO_CANCEL;
        messageNotificatioManager.notify(messageNotificationID, messageNotification);
        messageNotificationID++;
    }


    /**
     * packName  应用的包名
     * 返回值
     */
    public static boolean isAppAlive(Context context, String packageName) {
        ActivityManager activityManager =
                (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos
                = activityManager.getRunningAppProcesses();
        for (int i = 0; i < processInfos.size(); i++) {
            if (processInfos.get(i).processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    List<String> disableNames = new ArrayList<String>();

//    private void updateAPPIcon() {
//        String dataBeanStr = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
//
//        ConfigBean.DataBean dataBean = new Gson().fromJson(dataBeanStr, ConfigBean.DataBean.class);
//        if (dataBean != null) {
//            String baseAppLog = dataBean.getApplog();
//            if (!ObjectUtils.isEmpty(baseAppLog)) {
//                String applog = new String(EncodeUtils.base64Decode(baseAppLog));
//                if (!ObjectUtils.isEmpty(applog)) {
//                    String activeName;
//                    String negativeName;
//                    disableNames.clear();
//                    if (ObjectUtils.equals(applog, "1")) {
//                        activeName = "com.uetoken.cn.festival_icon";
//                        negativeName = "com.uetoken.cn.default_icon";
//                    } else {
//                        activeName = "com.uetoken.cn.default_icon";
//                        negativeName = "com.uetoken.cn.festival_icon";
//                    }
//                    disableNames.add(negativeName);
//                    setAppIcon(activeName, disableNames);
//                }
//            }
//        }
//    }
//
//
//    public void setAppIcon(String activeName, List<String> disableNames) {
//
//        new AppIconNameChanger.Builder(this)
//                .activeName(activeName) // String
//                .disableNames(disableNames) // List<String>
//                .packageName(BuildConfig.APPLICATION_ID)
//                .build()
//                .setNow();
//    }
}
